package com.hengxinguotong.zhihuichengjian.ui.building;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AddContactsAndMessageAdapter;
import com.hengxinguotong.zhihuichengjian.bean.AddGroupPersonnelListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/1/14
 */

public class ConstructionUserSelectActivity extends BaseActivity implements AddContactsAndMessageAdapter.OnClickListener,
        AddContactsAndMessageAdapter.OnSendMessageListener{
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_p)
    ImageView ivP;
    @BindView(R.id.et_project)
    HXEditTextView etProject;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;

    private PullableRecyclerView dataRv;
    private static final int MSG_UPDATE_INFO = 0x110;
    private int pageIndex = 1;
    private AddContactsAndMessageAdapter adapter;
    private List<User> mUsers;
    private List<User> selectUsers;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_INFO:
                    List<User> datas = (List<User>) msg.obj;
                    process(datas);
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_select_construction);
        ButterKnife.bind(this);
        List<User> noticedPersons = (List<User>) getIntent().getSerializableExtra("noticedPersons");
        if (selectUsers == null) {
            selectUsers = new ArrayList<User>();
            selectUsers.addAll(noticedPersons);
        }
        initView();
        initData();
    }

    private void initView() {
        etProject.addTextChangedListener(searchTextWatcher);

        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);

        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        mUsers = new ArrayList<>();
        adapter = new AddContactsAndMessageAdapter(this, mUsers);
        dataRv.setAdapter(adapter);
        adapter.setOnClickListener(this);
        adapter.setOnSendMessageListener(this);
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        dataRv.setItemAnimator(new DefaultItemAnimator());
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            pageIndex = mUsers.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private void initData(){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getPersonnelList(getResources().getString(R.string.loading));
            }
        }, 500);
    }

    private void getPersonnelList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
//            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("name", etProject.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/notice/listUser/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AddGroupPersonnelListRes res = gson.fromJson(json, AddGroupPersonnelListRes.class);
                    if(res.getStatus() == 1){
                        List<User> datas = res.getValue();
                        if(datas == null){
                            datas = new ArrayList<User>();
                        }
                        Message msg = mHandler.obtainMessage();
                        msg.what = MSG_UPDATE_INFO;
                        msg.obj = datas;
                        msg.sendToTarget();
                    }else {
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                }else {
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    private void process(List<User> datas){
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            mUsers = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            mUsers.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        filter();
        adapter.setDataList(mUsers);
    }

    private void filter(){
        for(User user1:mUsers){
            for (User user2:selectUsers){
                if(user1.getUserId().equals(user2.getUserId())){
                    user1.setChecked(true);
                    user1.setStatus(user2.getStatus());
                }
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.save_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                Intent intent = getIntent();
                if (selectUsers.size() != 0) {
                    intent.putExtra("selectNoticers", (Serializable) selectUsers);
                    setResult(1, intent);
                }
                finish();
                break;
        }
    }


    private TextWatcher searchTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            pageIndex = 1;
            initData();
        }
    };

    @Override
    public void onSendMessage(int position, boolean isChecked) {
        if(isChecked){
            mUsers.get(position).setStatus(1);
        }else {
            mUsers.get(position).setStatus(0);
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // 刷新操作
                adapter.setDataList(mUsers);
            }
        });
    }

    @Override
    public void onClick(Object o) {
        int position = (int) o;
        User user = mUsers.get(position);
        if(user.isChecked()){
            user.setChecked(false);
            selectUsers.remove(user);
        }else {
            user.setChecked(true);
            selectUsers.add(user);
        }
        adapter.setDataList(mUsers);
    }
}
